package org.web2024.interceptor;
import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.web2024.cnofig.CourseSelectionConfig;
import org.web2024.dao.Result;

import java.time.LocalDateTime;

@Component
@Slf4j
public class SelectcourseCheckinterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    /*
     * 在请求处理之前进行预处理，检查当前时间是否处于选课时间段内
     *
     * @param request  HttpServletRequest对象，表示当前请求
     * @param response HttpServletResponse对象，用于发送响应
     * @param handler  请求处理器对象
     * @return 如果当前时间在选课时间段内，则返回true，否则返回false
     * @throws Exception 如果在处理过程中发生异常
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        String startTime = (String)redisTemplate.opsForHash().get("currentterm", "starttime");
        String endTime = (String)redisTemplate.opsForHash().get("currentterm", "endtime");
        if (startTime == null||endTime==null) {
            Result error = Result.fail("未开始选课学期");
            String NoSelectTime = JSONObject.toJSONString(error);
            response.getWriter().write(NoSelectTime);
            return false;
        }
        // 解析选课开始时间
        LocalDateTime start = LocalDateTime.parse(startTime);
        // 解析选课结束时间
        LocalDateTime end = LocalDateTime.parse(endTime);
        // 检查当前时间是否在选课时间段内
        if (now.isBefore(start) || now.isAfter(end)) {
            // 如果不在选课时间段内，发送错误响应并返回false
            Result error = Result.fail("选课时间未到，请等待选课时间");
            String NoSelectTime = JSONObject.toJSONString(error);
            response.getWriter().write(NoSelectTime);
            return false;
        }
        // 如果在选课时间段内，返回true
        return true;
    }
}
